package com.fy.core.upload;

import cn.hutool.json.JSONUtil;
import com.fy.core.vo.ApiRest;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author hxd
 * @version 1.0
 * @ClassName UploadController
 * @date 2023/5/30 17:36
 * @since 1.0
 */
@RestController
@CrossOrigin
public class UploadController {
    @Value("r7qJxU_J3z5XE5B95ZJy3JFgQhLOWxHseUQ0sozX")
    private String AK;
    
    @Value("KgobBowG3lq3MswH0HVbKJudCWgUGT7gpV7fhf6H")
    private String SK;

    @Value("huoxudong")
    private String BUCKET;

    @Value("http://rvgwlf7ij.hn-bkt.clouddn.com")
    private String HOST;

    @PostMapping("/upload")
    @ResponseBody
    public ApiRest upload(MultipartFile img){
        try {
            byte[] bytes = img.getBytes();
            String originalFilename = img.getOriginalFilename();
            System.out.println("originalFilename = " + originalFilename);
            // Region必须指定为bucket设置的地址
            Configuration cfg = new Configuration(Region.huanan());
            cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
            UploadManager uploadManager = new UploadManager(cfg);

            String key = null;
            //获取令牌
            Auth auth = Auth.create(AK, SK);
            String upToken = auth.uploadToken(BUCKET);
            Response response = uploadManager.put(bytes, key, upToken);
            String jsonStr = response.bodyString();

            //json  -> java对象
            DefaultPutRet obj = JSONUtil.toBean(jsonStr, DefaultPutRet.class);
            //上传成功后的的文件名
            String url = HOST+obj.key;
            System.out.println("url = " + url);
            //save url to db
            return ApiRest.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            return ApiRest.failure();
        }


    }
}
